<template>
  <div>
    <nav-bar>
      <template v-slot:default>购物车(<small>{{ $store.state.cartCount }}</small>)</template>
    </nav-bar>
    <div class="cart-box">
      <div class="cart-body">
        <van-checkbox-group ref="checkboxGroup" v-model="result" @change="groupChange">
          <van-swipe-cell v-for="item in carList" :key="item.id" :right-width="50">
            <div class="good-item">
              <van-checkbox :name="item.id"/>
              <div class="good-img"><img v-lazy="item.goods.cover_url" alt=""></div>
              <div class="good-desc">
                <div class="good-title">
                  <span>{{ item.goods.title }}</span>
                  <span><small>库存：{{ item.goods.stock }}</small></span>
                </div>
                <div class="good-btn">
                  <div class="price"><small>¥</small>{{ item.goods.price }}<small>.00</small></div>
                  <van-stepper integer :min="1" :max="item.goods.stock" :model-value="item.num" :name="item.id"
                               async-change
                               @change="onChange"
                  />
                </div>
              </div>
            </div>
            <template #right>
              <van-button
                  square
                  icon="delete"
                  type="danger"
                  class="delete-button"
                  @click="delGoods(item.id)"
              />
            </template>
          </van-swipe-cell>
        </van-checkbox-group>
      </div>
      <van-submit-bar class="submit-all" :price="total*100" button-text="结算" @submit="onSubmit">
        <van-checkbox :checked="isCheckAll" @click="doCheckAll">全选</van-checkbox>
      </van-submit-bar>

      <div class="empty" v-if="!carList.length">
        <img class="empty-cart" src="~assets/images/empty-car.png" alt="空购物车">
        <div class="title">购物车空空如也</div>
        <van-button round color="#1baeae" type="primary" block @click="goTo">前往选购</van-button>
      </div>

    </div>

  </div>
</template>

<script>
import {computed, defineComponent, onMounted, reactive, ref, toRefs} from 'vue'
import NavBar from "components/common/navbar/NavBar"
import {useRouter} from "vue-router";
import {useStore} from "vuex";
import {Toast} from "vant";
import {checkedCart, delCart, editCart, getCarts} from "../../network/cart";

export default defineComponent({
  name: 'ShopCart',
  components: {
    NavBar
  },
  setup() {
    const router = useRouter()
    const store = useStore()
    // 数据模型(购物车列表数据)
    const curCart = reactive({
      carList: [],
      result: [],// 购物车Id数组
      isCheckAll: false
    })
    // let isCheckAll = ref(true)
    // 初始化购物车数据
    const initCarList = () => {
      Toast.loading({
        message: '加载中...',
        forbidClick: true,
      });
      // 从api接口获取购物车数据
      getCarts('include=goods').then(res => {
        // 将接口取到的数据赋值给数据模型
        curCart.carList = res.data
        /*let a = res.data.filter(n => {
          return n.is_checked == 1
        })
        console.log(a)
        let b = a.map(n => {
          return n.id
        })
        console.log(b)*/
        // 获取列表中is_checked为1的项，并将这些项的id加入到数组
        curCart.result = res.data.filter(n => n.is_checked === 1).map(n => n.id)
        Toast.clear()
        // curCart.isCheckAll = curCart.result.length === curCart.carList.length
        // console.log('ss:' + isCheckAll)
      })
    }
    onMounted(() => {
      initCarList()
    })

    // 异步改变购物车单个商品数量
    const onChange = (value, detail) => {
      Toast.loading({
        message: '修改中...',
        forbidClick: true,
      });
      // console.log(value)
      // console.log(detail)
      editCart(detail.name, {num: value}).then(() => {
        // 将在onMounted中的list中的商品数量也要改变
        curCart.carList.map((item) => {
          if (item.id === detail.name) {
            item.num = value
          }
        })
        Toast.clear()
      })
    }
    //
    const groupChange = (result) => {
      // console.log(result)
      // curCart.result=result
      curCart.isCheckAll = result.length === curCart.carList.length

      // 改变数据库购物车的选中状态
      checkedCart({cart_ids: result}).then(res => {
        // console.log(res.status)
      })
    }

    // 全选
    const doCheckAll = () => {
      if (!curCart.isCheckAll) {
        curCart.isCheckAll = true
        curCart.result = curCart.carList.map(item => item.id)
      } else {
        curCart.isCheckAll = false
        curCart.result = []
      }
    }
    // 删除商品
    const delGoods = (id) => {
      delCart(id).then(() => {
        initCarList()//重新获取购物车数据
        store.dispatch('updateCart')// 改变vuex中购物车的状态数量
      })
    }
    // 通过计算属性计算总价
    const total = computed(() => {
      let sum = 0
      curCart.carList.filter(item => curCart.result.includes(item.id))
          .map(item => sum += item.goods.price * item.num)
      return sum
    })
    // 结算按钮，创建订单
    const onSubmit = () => {
      // 判断是否存在选中的
      if (curCart.result.length === 0) {
        Toast.fail("请选择商品进行结算")
      }else{
        router.push({path:'/createorder'})
      }
    }

    // 前往购物
    const goTo = () => {
      router.push({path: '/home'})
    }
    return {
      ...toRefs(curCart),
      goTo,
      onChange,
      groupChange,
      doCheckAll,
      delGoods,
      total,
      onSubmit
    }
  }
})
</script>

<style scoped lang="scss">
.cart-box {
  .cart-body {
    margin: 45px 0 0 0;
    padding-left: 10px;

    .good-item {
      display: flex;

      .good-img {
        img {
          width: 100px;
          height: auto;
        }
      }

      .good-desc {
        display: flex;
        flex-direction: column;
        justify-content: space-between;
        flex: 1;
        padding: 20px;

        .good-title {
          display: flex;
          justify-content: space-between;
        }

        .good-btn {
          display: flex;
          justify-content: space-between;

          .price {
            font-size: 16px;
            color: red;
            line-height: 28px;
          }

          .van-icon-delete {
            font-size: 20px;
            margin-top: 4px;
          }
        }
      }
    }

    .delete-button {
      width: 50px;
      height: 100%;
    }
  }

  .empty {
    width: 50%;
    margin: 0 auto;
    text-align: center;
    margin-top: 200px;

    .empty-cart {
      width: 150px;
      margin-bottom: 20px;
    }

    .van-icon-smile-o {
      font-size: 50px;
    }

    .title {
      font-size: 16px;
      margin-bottom: 20px;
    }
  }

  .submit-all {
    margin-bottom: 50px;
    z-index: 10 !important;

    .van-checkbox {
      margin-left: 0
    }

    .van-submit-bar__text {
      margin-right: 10px
    }

    .van-submit-bar__button {
      background: red;
    }
  }

  .van-checkbox__icon--checked .van-icon {
    background-color: red;
    border-color: red;
  }
}
</style>